<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="生产单号" prop="produceNo">
                <el-input v-model="queryParams.produceNo" placeholder="请输入生产单号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="姓名" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入姓名" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="项目编号" prop="projectCode">
                <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="产品名称" prop="goodsName">
                <el-input v-model="queryParams.goodsName" placeholder="请输入产品名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="产品型号" prop="gongxuModel">
        <el-input v-model="queryParams.gongxuModel" placeholder="请输入产品型号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
            <el-form-item label="工序名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="图纸号" prop="shuoming">
                <el-input v-model="queryParams.shuoming" placeholder="请输入图纸号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="生产产品名称" prop="gongxuName">
                <el-input v-model="queryParams.gongxuName" placeholder="请输入生产产品名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="生产产品型号" prop="gongxuModel">
                <el-input v-model="queryParams.gongxuModel" placeholder="请输入生产产品型号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="车间" prop="deptName">
                <el-select v-model="queryParams.deptName" placeholder="请选择车间" style="width: 100%"
                    @change="handshopChange">
                    <el-option v-for="(item, index) in workshopOptions" :key="index" :label="item.label"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="报工状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择报工状态" clearable style="width: 180px">
                    <el-option v-for="dict in dict.type.baogong_status" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item> -->
            <!--<el-form-item label="报工时间" prop="doTime">
        <el-date-picker clearable v-model="queryParams.doTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择报工时间">
        </el-date-picker>
      </el-form-item>-->
            <el-form-item label="报工时间">
                <el-date-picker v-model="dateRange" style="display: flex;" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button> -->
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8" v-if="!projectCode">
            <el-col :span="1.5">
                <el-popconfirm title="确认选择批量质检的数据项？" @confirm="handleZhijianAll({})">
                    <el-button slot="reference" type="success" plain icon="el-icon-delete" size="mini"
                        :disabled="multiple" v-hasPermi="['develop:reportRecord:pilQualitBnt']">批量报工质检合格</el-button>
                </el-popconfirm>
            </el-col>
            <el-col :span="1.5">
                <el-popconfirm title="确认选择批量质检的数据项？" @confirm="handleZhijianAllNo({})">
                    <el-button slot="reference" type="danger" plain icon="el-icon-delete" size="mini"
                        :disabled="multiple" v-hasPermi="['develop:reportRecord:pilQualitBnt']">批量报工质检 不合格</el-button>
                </el-popconfirm>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
            :max-height="tableMaxHeight" @sort-change="handleSortChange" show-summary :summary-method="getSummaries">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column sortable label="生产单号" align="center" prop="produceNo" show-overflow-tooltip />
            <el-table-column sortable label="项目编号" align="center" prop="projectCode" show-overflow-tooltip />
            <el-table-column sortable label="产品编号" align="center" prop="goodsCode" />
            <el-table-column sortable label="产品名称" align="center" prop="goodsName" show-overflow-tooltip />
            <el-table-column sortable label="产品型号" align="center" prop="goodsModel" />
            <el-table-column sortable label="工序名称" align="center" prop="name" />
            <el-table-column sortable label="图纸号" align="center" prop="shuoming" />
            <el-table-column sortable label="生产产品名称" align="center" prop="gongxuName" />
            <el-table-column sortable label="生产产品型号" align="center" prop="gongxuModel" />
            <el-table-column sortable label="车间" align="center" prop="deptName" />
            <el-table-column sortable label="姓名" align="center" prop="userName" />
            <el-table-column sortable label="报工时间" align="center" prop="doTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.doTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column sortable label="报工数量" align="center" prop="count" />
            <el-table-column sortable label="单价" align="center" prop="money" />
            <el-table-column sortable label="合格数量" align="center" prop="successCount" />
            <el-table-column sortable label="不合格数量" align="center" prop="errorCount" />
            <el-table-column sortable label="合格总价" align="center" prop="allMoney" />
            <el-table-column sortable label="合格率(%)" align="center" prop="successLv" />
            <!-- <el-table-column align="center" label="状态" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.baogong_status" :value="scope.row.status" />
                </template>
            </el-table-column> -->
            <!--el-table-column sortable label="质检日期" align="center" prop="zhijianDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.zhijianDate, '{y}-{m}-{d}') }}</span>
        </template>
        </el-table-column>
        <el-table-column sortable label="质检人" align="center" prop="zhijianUser" /> -->
            <el-table-column label="备注" align="center" prop="remark" />
            <!--<el-table-column label="巡检" align="center" prop="iszhijian" >
          <template slot-scope="scope">
             <span>{{ scope.row.iszhijian == '1' ? '已巡检' : ' ' }}</span>
          </template>
        </el-table-column>-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-set-up" v-hasPermi="['develop:pollingBnt:Bnt']"
                        @click="qualityTestingProcess(scope.row)">巡检
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-if="scope.row.status == 1" v-hasPermi="['develop:reportRecord:editBnt']">修改</el-button>
                    <el-button size="mini" v-if="!scope.row.errorCount" type="text" icon="el-icon-edit"
                        @click="zhijian(scope.row)" v-hasPermi="['develop:reportRecord:qualityBnt']">质检</el-button>
                    <el-popconfirm :title="`确认删除当前数据项？`" @confirm="handleDelete(scope.row)" style="margin-left: 10px;">
                        <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"
                            v-if="scope.row.status == 1" v-hasPermi="['develop:reportRecord:removeBnt']">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        <factory-test-quality-process ref="qualityTestingProcess" @ok="getList"> </factory-test-quality-process>
        <goodsSaledoGongxuUserMoney-form ref="form" @ok="getList"></goodsSaledoGongxuUserMoney-form>
        <zhijianGongxu-form ref="zhijianForm" @ok="getList"></zhijianGongxu-form>
    </div>
</template>

<script>
import { deleteAction, getAction, downloadFile, accAdd } from '@/api/manage'
import GoodsSaledoGongxuUserMoneyForm from '@/views/develop/goodsSaledoGongxuUserMoney/module/GoodsSaledoGongxuUserMoneyForm'
import ZhijianGongxuForm from '@/views/develop/goodsSaledoGongxuUserMoney/module/ZhijianGongxuForm'
import FactoryTestQualityProcess from "@/views/develop/factory/factoryTestQuality/FactoryTestQualityProcess.vue";
import { list } from "@/api/develop/goodsSaledoGongxuUserMoney";

export default {
    name: "PortionBaoGongList",
    dicts: ['baogong_status'],
    components: {
        GoodsSaledoGongxuUserMoneyForm,
        ZhijianGongxuForm,
        FactoryTestQualityProcess
    },
    props: {
        projectCode: {
            type: [String],
            required: true,
            default: ''
        },
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 报工列表格数据
            dataList: [],
            dateRange: [],
            // 查询参数
            queryParams: {
                name: null,
                shuoming: null,
                goodsName: null,
                deptName: null,
                gongxuModel: null,
                projectCode: null,
                produceNo: null,
                pageNum: 1,
                pageSize: 10,
                xuhao: null,
                doTime: null,
                userId: null,
                userName: null,
                money: null,
                count: null,
                allMoney: null,
                parentId: null,
                successCount: null,
                errorCount: null,
                successLv: null,
                status: '2',
                zhijianDate: null,
                zhijianUser: null,
                zhijianId: null,
                gongxuName: null,
            },
            url: {
                list: '/goodsSaledoGongxuUser/goodsSaledoGongxuUser/list',
                removeUpdate: '/goodsSaledoGongxuUserMoney/goodsSaledoGongxuUserMoney/removeUpdate/',
                export: '/goodsSaledoGongxuUserMoney/goodsSaledoGongxuUserMoney/export',
                zhijianAllUpdate: '/goodsSaledoGongxuUserMoney/goodsSaledoGongxuUserMoney/zhijianAllUpdate/',
                zhijianAllNoUpdate: '/goodsSaledoGongxuUserMoney/goodsSaledoGongxuUserMoney/zhijianAllNoUpdate/',
                userTreeSelect: '/system/dept/userTreeSelect'
            },
            workshopOptions: [

            ],
            tableMaxHeight: window.innerHeight - 320,
        };
    },
    watch: {
        'projectCode': {
            handler(newVal, oldVal) {
                console.log("projectCode", newVal);
                if (newVal) {
                    this.queryParams.projectCode = newVal;
                    this.getList();
                }
            },
            deep: true,
            immediate: true
        },
    },
    created() {
        this.getList();
        this.getUser();
        window.addEventListener('resize', this.getTableHeight);
    },
    destroyed() {
        window.removeEventListener('resize', this.getTableHeight)
    },
    methods: {
        qualityTestingProcess(row) {
            if (row.status === '0') {
                this.$refs.qualityTestingProcess.showByProcess(row, true);
            } else {
                this.$refs.qualityTestingProcess.showByProcess(row, false);
            }
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) => Number(item[column.property]));
                // 只合计amount1和amount3，想合并哪些列就在这里指定
                if (column.property === "count" || column.property === "money" || column.property === "allMoney" || column.property === "successCount" || column.property === "errorCount") {
                    sums[index] = values.reduce((prev, curr) => {

                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return accAdd(prev, curr);
                        } else {
                            return prev;
                        }
                    }, 0);
                }
            });
            return sums;
        },
        handshopChange(e) {
            // 查找匹配的选项，不仅匹配value，也匹配id
            const selected = this.workshopOptions.find(item => item.value === e || item.id === e);
            if (selected) {
                // 设置表单的部门ID和名称
                // this.queryParams.deptId = selected.id;
                this.queryParams.deptName = selected.label;
            }
        },
        getUser() {
            let that = this;
            getAction(that.url.userTreeSelect, { parentId: '57d779853f0f4d14b03d51db30099456' }).then(res => {
                that.workshopOptions = res.data;
            })
        },
        /** 排序触发事件 */
        handleSortChange(column, prop, order) {
            this.queryParams.orderByColumn = column.prop;
            this.queryParams.isAsc = column.order;
            this.handleQuery();
        },
        /** 查询报工列列表 */
        getList() {
            this.loading = true;
            list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                //getAction(this.url.list, this.queryParams).then(response => {
                this.dataList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        getTableHeight() {
            this.tableHeight = window.innerHeight - 320
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.$refs.form.handleAdd();
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.$refs.form.handleUpdate(row);
        },
        zhijian(row) {
            this.$refs.zhijianForm.zhijianShow(row);
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            deleteAction(this.url.removeUpdate, ids).then(response => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            let that = this;
            that.loading = false;
            that.$confirm('是否确认报工信息表?', "确认", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                downloadFile('/goodsSaledoGongxuUserMoney/goodsSaledoGongxuUserMoney/exportGz', that.queryParams);
            });
        },
        handleZhijianAll() {
            const ids = this.ids;
            deleteAction(this.url.zhijianAllUpdate, ids).then(response => {
                this.getList();
                this.$modal.msgSuccess("批量质检成功！");
            }).catch(() => { });
        },
        handleZhijianAllNo() {
            const ids = this.ids;
            deleteAction(this.url.zhijianAllNoUpdate, ids).then(response => {
                this.getList();
                this.$modal.msgSuccess("批量质检成功！");
            }).catch(() => { });
        },
    }
};
</script>
